package com.bitdf.txing.group.controller;

import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.dev33.satoken.annotation.SaCheckSafe;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bitdf.txing.common.enume.TxCodeEnume;
import com.bitdf.txing.common.interceptor.LoginInterceptor;
import com.bitdf.txing.common.to.UserTo;
import com.bitdf.txing.common.utils.R;
import com.bitdf.txing.group.entity.GroupInfoEntity;
import com.bitdf.txing.group.entity.GroupMemberEntity;
import com.bitdf.txing.group.feign.EsFeignService;
import com.bitdf.txing.group.service.GroupInfoService;
import com.bitdf.txing.group.service.GroupMemberService;
import com.bitdf.txing.group.to.GroupInfoTo;
import com.bitdf.txing.group.valid.SaveVaild;
import com.bitdf.txing.group.valid.UpdateValid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author Lizhiwei
 * @email 123@qq.com
 * @date 2022-09-05 16:02:12
 */
@RestController
@RequestMapping("${txing.request.path.group}/info")
public class GroupInfoController {
    @Autowired
    private GroupInfoService groupInfoService;
    @Autowired
    private GroupMemberService groupMemberService;
    @Autowired
    private EsFeignService esFeignService;

    /**
     * 发起组团
     */
    @RequestMapping("/save")
    @SaCheckLogin
    public R save(@Validated(value = {SaveVaild.class}) @RequestBody GroupInfoTo groupInfoTo, BindingResult result) throws IOException {
        if (result.hasErrors()) {
            Map<String, String> errors = result.getFieldErrors().stream().collect(Collectors.toMap(FieldError::getField, FieldError::getDefaultMessage));
            return R.error(TxCodeEnume.COMMON_SUBMIT_DATA_EXCEPTION).put("data", errors);
        }
        Boolean bool = groupInfoService.saveGroupInfoTo(groupInfoTo);
        return R.ok();
    }

    /**
     * 修改组团信息
     */
    @SaCheckLogin
    @RequestMapping("/update")
    public R update(@Validated(value = {UpdateValid.class}) @RequestBody GroupInfoTo groupInfo, BindingResult result) throws IOException {
        if (result.hasErrors()) {
            Map<String, String> errors = result.getFieldErrors().stream().collect(Collectors.toMap(FieldError::getField, FieldError::getDefaultMessage));
            return R.error(TxCodeEnume.COMMON_SUBMIT_DATA_EXCEPTION).put("data", errors);
        }
        R r = esFeignService.updateGroup(groupInfo);

        return r.getCode() == 0 ? R.ok() : R.error(TxCodeEnume.COMMON_SYSTEM_UNKNOWN_EXCEPTION);
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    @SaCheckLogin
    public R delete(@RequestBody Long[] ids) {
        groupInfoService.removeByIds(Arrays.asList(ids));
        return R.ok();
    }

    /**
     * 组团点赞与取消
     *
     * @param groupId
     * @return
     */
    @RequestMapping("/like")
    @SaCheckLogin
    public R modifyLike(@RequestParam("groupId") Long groupId) throws IOException {
        Boolean flag = groupInfoService.modifyLikeByGroupId(groupId);
        return flag ? R.ok() : R.error(TxCodeEnume.COMMON_SYSTEM_UNKNOWN_EXCEPTION);
    }

    /**
     * 组团浏览数增加
     *
     * @param groupId
     * @return
     */
    @GetMapping("/view")
    public R modifyViewCount(@RequestParam("groupId") Long groupId) throws IOException {
        Boolean flag = groupInfoService.modifyViewCount(groupId);
        return flag ? R.ok() : R.error(TxCodeEnume.COMMON_SYSTEM_UNKNOWN_EXCEPTION);
    }

    /**
     * 关闭组团活动
     *
     * @param groupId
     * @return
     * @throws IOException
     */
    @SaCheckLogin
    @GetMapping("/closeGroup")
    public R closeGroup(@RequestParam("groupId") Long groupId) throws IOException {
        //TODO 获取真实用户id
        UserTo userTo = LoginInterceptor.threadLocal.get();
        if (groupMemberService.getOne(new QueryWrapper<GroupMemberEntity>().eq("group_id", groupId).eq("user_id", userTo.getId())).getLeaderStatus() != 1) {
            return R.error(TxCodeEnume.USER_NOT_PERM_EXCEPTION);
        }
        R r = esFeignService.closeGroup(groupId);
        return r;
    }

    /**
     * 将es中的数据同步到数据库
     *
     * @return
     */
    @RequestMapping("/sync/database")
    public R syncDatabase(@RequestBody List<GroupInfoTo> list) throws Exception {
        boolean flag = groupInfoService.syncDatabase(list);
        return flag ? R.ok() : R.error(TxCodeEnume.COMMON_SYSTEM_UNKNOWN_EXCEPTION);
    }


    //TODO 删除组团（要删除成员信息）


}
